﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using System.Diagnostics;
using DevExpress.XtraEditors;
using Sunboxsoft.ASMS.Client.UI.Properties;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
namespace Sunboxsoft.ASMS.Client.UI.Storage
{
    /// <summary>
    /// 出入库记录
    /// </summary>
    public partial class StockChangedRecordListView : UserControl, IView
    {
        Promise _promise = new Promise();
        //选择的商品
        WebRef.VMaterial _vMaterial = null;

        //当前页  
        private int _pageIndex = 0;
        //总共几页
        private int _pageCount = 0;

        public StockChangedRecordListView()
        {
            InitializeComponent();
            this.GCData.EmbeddedNavigator.ButtonClick += new DevExpress.XtraEditors.NavigatorButtonClickEventHandler(EmbeddedNavigator_ButtonClick);
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("view", Resources.isView, "查看", btnReview_Click) { IsShow = false })
               .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Active(WinForm.ViewActiveArgs args)
        {
            _promise
                .Then(() =>
                {
                    ctlSearchLookUpEditWareHouse.BindEWarehouse(_promise, null, true);
                })
                .Then(() =>
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        ctlSearchLookUpEditStockChangeQueryType.BindIntCodeTextItem(Domain.Constant.StockChangeTypes.EnumerateAll(),
                            Domain.Constant.StockChangeTypes.AllItem, true);
                        _promise.Resolve();
                    }));
                })
                .Then(RefreshData)
                .Run(null);
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.View is Pickers.MaterialPicker)
                {
                    _vMaterial = args.ClosedArgs.Data as WebRef.VMaterial;
                    this.ctlBtnQryMaterial.Text = _vMaterial.Name;
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("出入库记录");
        }
        #endregion

        #region Method
        /// <summary>
        /// 判断查询时选择日期范围是否合理
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        private bool GetDataRange(out DateTime? beginTime, out DateTime? endTime)
        {
            if (!string.IsNullOrEmpty(this.ctlDateBegin.Text))
            {
                beginTime = Convert.ToDateTime(this.ctlDateBegin.Text);
            }
            else
            {
                beginTime = null;
            }
            if (!string.IsNullOrEmpty(this.ctlDateEnd.Text))
            {
                endTime = Convert.ToDateTime(this.ctlDateEnd.Text);
            }
            else
            {
                endTime = null;
            }

            if (beginTime != null && endTime != null)
            {
                if (beginTime > endTime)
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 获取每页条数限制
        /// </summary>
        /// <returns></returns>
        private int GetPageLimit()
        {
            int pagesize = 25;
            return pagesize;
        }
        /// <summary>
        /// 数据列表绑定
        /// </summary>
        private void RefreshData()
        {
            Guid? wareHouseId = null, materialId = null;
            WebRef.EWarehouse itemWarehouse = ctlSearchLookUpEditWareHouse.GetSelectedValue<WebRef.EWarehouse>();
            if (itemWarehouse != null)
            {
                wareHouseId = itemWarehouse.Id;
            }
            if (_vMaterial != null)
            {
                materialId = _vMaterial.Id;
            }
            DateTime? beginTime = null;
            DateTime? endTime = null;
            if (!GetDataRange(out beginTime, out endTime))
            {
                UIContext.Current.ViewManager.ShowWarning("请选择正确的日期范围!");
            }
            UIContext.Current.InvokeAsync(() =>
            {
                PagedResult<WebRef.VStockChangedRecord> result = new Service.QueryService().QueryStockChangedRecordPagedList(
                    ModuleContext.Current.BusinessId,
                    ModuleContext.Current.StationId,
                    wareHouseId,
                    materialId,
                    beginTime,
                    endTime,
                    this.ctlSearchLookUpEditStockChangeQueryType.GetSelectedValue<Domain.IntCodeTextItem>().GetCode(),
                   _pageIndex * GetPageLimit(),
                    GetPageLimit());
                this.BeginInvoke(new Action<PagedResult<WebRef.VStockChangedRecord>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        this.GCData.Paginate<WebRef.VStockChangedRecord>(result, out _pageIndex, out _pageCount);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Reject();
                    }
                }), result);
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        private void btnReview_Click(object obj1, object obj2)
        {

        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        private void btnRefresh_Click(object obj1, object obj2)
        {
            _pageIndex = 0;
            RefreshData();
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            e.UpdatePageIndex(_pageCount, ref _pageIndex);
            RefreshData();
        }
        /// <summary>
        /// 选择商品&清除所选商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnQryMaterial_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.Equals("clear"))
            {
                this.ctlBtnQryMaterial.Text = "";
                _vMaterial = null;
            }
            else
            {
                UIContext.Current.ViewManager.PopupView(new Pickers.MaterialPicker(Domain.Constant.CommonStatus.Enabled), new PopupViewArgs("选择商品"));
            }
        }
        #endregion
    }
}
